#import "ApplemusicauthPlugin_tPlugin.h"
#import <MediaPlayer/MediaPlayer.h>
#import <StoreKit/StoreKit.h>

@implementation ApplemusicauthPlugin_tPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"applemusicauth_plugin_t"
            binaryMessenger:[registrar messenger]];
  ApplemusicauthPlugin_tPlugin* instance = [[ApplemusicauthPlugin_tPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getPlatformVersion" isEqualToString:call.method]) {
    result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  } else if ([@"getAppleMusicAuth" isEqualToString:call.method]) {
      NSString * developerToken = call.arguments[@"developerToken"];
      [self userAuth:developerToken result:result];
  }
  else {
    result(FlutterMethodNotImplemented);
  }
}



//用户是否已经授权
- (void)userAuth:(NSString *)developerToken result:(FlutterResult)result  {

    SKCloudServiceAuthorizationStatus status = [SKCloudServiceController authorizationStatus];
    
    if (status == SKCloudServiceAuthorizationStatusNotDetermined) {
        [SKCloudServiceController requestAuthorization:^(SKCloudServiceAuthorizationStatus status) {
            if (status == SKCloudServiceAuthorizationStatusAuthorized) {
                NSLog(@"用户已授权Apple Music");
                [self userSubscribeStats:developerToken result:result];
            } else {
                NSLog(@"用户未授权Apple Music");
                [self sendError:@"1" result:result];
            }
        }];
    }
    else if (status == SKCloudServiceAuthorizationStatusDenied) {
        NSLog(@"用户已拒绝授权Apple Music");
        [self sendError:@"2" result:result];
    }
    else if (status == SKCloudServiceAuthorizationStatusRestricted) {
        NSLog(@"用户已限制授权Apple Music");
        [self sendError:@"3" result:result];
    }
    else if (status == SKCloudServiceAuthorizationStatusAuthorized) {
        NSLog(@"用户已授权Apple Music");
        [self userSubscribeStats:developerToken result:result];
    }
}

//用户是否已经订阅
- (void)userSubscribeStats:(NSString *)developerToken result:(FlutterResult)result {
    SKCloudServiceController *cloudServiceController = [[SKCloudServiceController alloc] init];
    [cloudServiceController requestCapabilitiesWithCompletionHandler:^(SKCloudServiceCapability capabilities, NSError * _Nullable error) {
        if (error != NULL) {
            // 处理错误
            NSLog(@"err = %@",error.description);
            [self sendError:@"4" result:result];
        } else {
            
            BOOL isSub = NO;
            if (capabilities == SKCloudServiceCapabilityNone) {
                NSLog(@"SKCloudServiceCapabilityNone 表示没有订阅吧");
            } else if (capabilities == SKCloudServiceCapabilityMusicCatalogSubscriptionEligible) {
                NSLog(@"表示设备允许订阅 Apple Music 目录。");
            } else {
                NSLog(@"表示用户已订阅 Apple Music，并且可以播放 Apple Music 目录中的音乐,并且可以将曲目添加到其云音乐库");
                isSub = YES;
            }
            
            
            if (isSub) {
                [self getUserToken:developerToken result:result];
            } else {
                //没有订阅
                [self sendError:@"5" result:result];
            }
        }
    }];
}

//获取userToken 根据DeveloperToken
- (void)getUserToken:(NSString *)developerToken result:(FlutterResult)result {
    SKCloudServiceController *cloudServiceController = [[SKCloudServiceController alloc] init];
    [cloudServiceController requestUserTokenForDeveloperToken:developerToken completionHandler:^(NSString * _Nullable userToken, NSError * _Nullable error) {
        if (error != NULL) {
            // 处理错误
            NSLog(@"err = %@",error.description);
            [self sendError:@"4" result:result];
        } else {
            // 成功获取用户令牌
            NSLog(@"User Token: %@", userToken);
            NSDictionary *dic = @{@"userToken":userToken};
            result(dic);
        }
    }];

}

- (void)sendError:(NSString *)msg result:(FlutterResult)result{
    NSDictionary *dic = @{@"error":msg};
    result(dic);
}

/**
返回的类型
userToken:userToken,
error:
 1:用户未授权Apple Music
 2:用户已拒绝授权Apple Music
 3:用户已限制授权Apple Music
 4:未知错误
 5:用户没有订阅
 
 */


@end
